//
//  NetworkSpinnerPlugin.swift
//  AntProj
//
//  Created by 陈宇 on 2017/4/27.
//  Copyright © 2017年 🐜. All rights reserved.
//

import Moya
import Result
import SwiftSpinner

public protocol NetworkSpinnerable: TargetType {
    
    var shouldDisplay: Bool { get }
}

final class NetworkSpinnerPlugin: PluginType {
    
    func willSend(_ request: RequestType, target: TargetType) {
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
        guard let target = target as? NetworkSpinnerable else {
            return
        }
        
        if target.shouldDisplay {
            SwiftSpinner.show("Connecting...".localized())
        }
    }
    
    func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
        guard let target = target as? NetworkSpinnerable else {
            return
        }
        
        if target.shouldDisplay {
            SwiftSpinner.show(duration: 0.7, title: "request finish...".localized())
        }
    }
    
}
